package com.wqs.tool.datainit.listener;

import com.google.gson.Gson;
import com.wqs.tool.datainit.entity.Task;
import com.wqs.tool.datainit.util.DataOprationUtils;
import com.wqs.tool.datainit.util.Dom4jUtils;
import com.wqs.tool.datainit.util.RedisUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;
@Slf4j
@Component
public class InitListener implements ApplicationListener<ContextRefreshedEvent> {
	
	@Autowired
	RedisUtils redisUtils;
	
	@Value("${spring.profiles.path}")
	String filePath;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		log.info("-------------------------------listener start-----------------------------------------------");
		Gson gson = new Gson();
		//从classpath下的task文件夹下获取所有的xml文件
		try {
			File taskFolder = new File(filePath);
			
			if(!taskFolder.exists()) {
	            throw new IllegalArgumentException("目录：tasks不存在.");
			}
			if(!taskFolder.isDirectory()){
	            throw new IllegalArgumentException(taskFolder+"不是目录。");
	        }
			File[] files=taskFolder.listFiles();
			
			for (File file : files) {
				Task task = Dom4jUtils.getTask(file);
				if (task != null) {
					log.info("***********************"+task.getName()+"*****start*******************");
					switch (task.getType()) {
						case "1" :
							DataOprationUtils.oprationTypeOne(redisUtils, task);
							break;
						case "2" :
							DataOprationUtils.oprationTypeTwo(redisUtils, task);
							break;
						case "3" :
							DataOprationUtils.oprationTypeThree(redisUtils, task);
					}
					log.info("***********************"+task.getName()+"*****end*******************");
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		log.info("-------------------------------listener end-----------------------------------------------");
	}

}
